package com.yunc.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunc.base.utils.R;
import com.yunc.modules.sys.entity.SysDept;
import com.yunc.modules.sys.entity.SysUserDept;
import com.yunc.modules.sys.service.ISysDeptService;
import com.yunc.modules.sys.service.ISysUserDeptService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 部门管理
 *
 * @author congcong tao
 * @create 2018/11/20 下午10:21
 */
@RestController
@RequestMapping("sysDept")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysDeptController {

    private final ISysDeptService sysDeptService;
    private final ISysUserDeptService sysUserDeptService;

    /**
     * 简单列表查询
     */
    @GetMapping("/list")
    public R list(SysDept sysDept) {
        QueryWrapper<SysDept> ew = new QueryWrapper<SysDept>()
                .orderByAsc("order_num");
        if (StringUtils.isNotEmpty(sysDept.getName())) {
            ew.like("name", sysDept.getName());
        }
        List<SysDept> sysDeptList = sysDeptService.list(ew);
        return R.ok().put("data", sysDeptList);
    }

    /**
     * 查询所有部门，树形结构，children，可通过name查询数
     */
    @GetMapping("/queryDeptList")
    public R queryDeptList(String name) {
        List<SysDept> sysDeptList = sysDeptService.queryDeptList(name);
        return R.ok().put("sysDeptList", sysDeptList);
    }

    /**
     * 查询当前用户部门，列表展示
     */
    @GetMapping("/queryCurrentUserDeptList")
    public R queryCurrentUserDeptList(String userId) {
        // 当前用户主键
        // 本人及所属子部门
        List<SysDept> sysDeptList = sysDeptService.queryUserDeptList(userId);
        return R.ok().put("sysDeptList", sysDeptList);
    }

    /**
     * 查询所有部门，树形结构，children，包含userId所选中的部门
     */
    @GetMapping("/queryDeptAndCheckedList")
    public R queryDeptAndCheckedList(String userId) {
        List<SysDept> sysDeptList = sysDeptService.queryDeptList("");
        // 查询所选部门
        List<String> checkedDeptIds;
        if (userId != null) {
            checkedDeptIds = sysUserDeptService.listDept(userId);
        } else {
            checkedDeptIds = new ArrayList<>();
        }
        return R.ok().put("sysDeptList", sysDeptList).put("checkedDeptIds", checkedDeptIds);
    }

    /**
     * 当前部门信息
     */
    @GetMapping("/info/{deptId}")
    public R info(@PathVariable String deptId) {
        SysDept dept = sysDeptService.getById(deptId);
        return R.ok().put("sysDept", dept);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @CacheEvict(value = {"user-dept-tree-key"}, allEntries = true)
    public R save(SysDept dept) {
        return sysDeptService.saveDept(dept);
    }

    /**
     * 修改
     */
    @PutMapping(value = "/update")
    @CacheEvict(value = {"user-dept-tree-key"}, allEntries = true)
    public R update(SysDept dept) {
        return sysDeptService.updateDept(dept);
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{deptId}")
    @CacheEvict(value = {"user-dept-tree-key"}, allEntries = true)
    public R delete(@PathVariable String deptId) {
        SysDept record = new SysDept();
        record.setParentId(deptId);
        QueryWrapper<SysDept> ew = new QueryWrapper<>(record);
        int count = sysDeptService.count(ew);
        if (count > 0) {
            return R.error("存在子部门，不允许删除");
        }
        // 其他用户有没有使用这个部门
        QueryWrapper<SysUserDept> cw = new QueryWrapper<>();
        cw.eq("dept_id", deptId);
        int userDeptCount = sysUserDeptService.count(cw);
        if (userDeptCount > 0) {
            return R.error("存在用户属于该部门，不允许删除");
        }
        boolean flag = sysDeptService.removeById(deptId);
        if (!flag) {
            return R.error();
        }
        return R.ok();
    }
}
